<template>
  <div class="reader">
    <!-- 面包屑区域 -->
    <BreadCrumb>读者管理</BreadCrumb>
    <div class="content">
      <!-- 卡片区域 -->
      <el-card>
        <!-- 搜索与添加区域 row(行)和 col(列) 是栅格布局-->
        <el-row :gutter="20">
          <el-col :span="10">
            <el-input placeholder="Please input" size="large" v-model="input"  class="input-with-select" @keydown.enter="searchReader">
              <template #prepend>
                <el-select v-model="select" style="width: 145px">
                  <el-option label="读者 ID" value="1" />
                  <el-option label="读者姓名关键词" value="2" />
                  <el-option label="最大可借数" value="3" />
                  <el-option label="最大可借天数" value="4" />
                </el-select>
              </template>
              <template #append>
                <el-button icon="el-icon-search" @click="searchReader"/>
              </template>
            </el-input>
          </el-col>
          <el-col :span="5">
            <el-button type="primary" size="large" @click="AddDialogVisible=true">添加</el-button>
          </el-col>
        </el-row>
        <!-- 用户列表区域 -->
        <el-table :data="data" border stripe>
          <el-table-column type="index" label="#" align="center"></el-table-column>
          <el-table-column prop="id" label="id" align="center" width="70px"/>
          <el-table-column prop="readername" label="读者姓名" align="center" width="170px" />
          <el-table-column prop="readertype" label="读者类型" align="center" width="170px"/>
          <el-table-column prop="sex" label="性别" align="center" width="170px"/>
          <el-table-column prop="max_num" label="最大可借数" align="center" width="170px"/>
          <el-table-column prop="days_num" label="最大可借天数" align="center" width="170px"/>
          <el-table-column label="操作" align="center">
            <!-- 作用域插槽，scope.row 可以拿到对应这一行的数据 -->
            <template #default="scope">
              <el-button  icon="el-icon-edit"  type="success" @click="handleEdit(scope.$index, scope.row)" :disabled="userStore.user.is_admin==='is' ? false : true">修改</el-button >
              <el-button icon="el-icon-delete" type="danger" @click="handleDelete(scope.$index, scope.row)" :disabled="userStore.user.is_admin==='is' ? false : true">删除</el-button >
            </template>
        </el-table-column>
        </el-table>
      </el-card>
    </div>

  <!-- 添加读者的对话框 -->
  <el-dialog v-model="AddDialogVisible" title="添加读者" width="45%" draggable @close="addDialogClosed">
    <el-form ref="addFormRef" :model="addForm" :rules="addRules" label-width="120px" size="large">
      <el-form-item label="读者姓名" prop="readername">
        <el-input v-model.trim="addForm.readername" />
      </el-form-item>
      <el-form-item label="读者类型" prop="readertype">
        <el-input v-model.trim="addForm.readertype" />
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <!-- <el-input v-model.trim="addForm.sex" /> -->
        <el-select v-model="addForm.sex" placeholder="请选择">
          <el-option label="男" value="男" />
          <el-option label="女" value="女" />
        </el-select>
      </el-form-item>
      <el-form-item label="最大可借数" prop="max_num">
        <el-input v-model.number="addForm.max_num" />
      </el-form-item>
      <el-form-item label="最大可借天数" prop="days_num">
        <el-input v-model.number="addForm.days_num" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="AddDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addReader(addFormRef)">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 修改读者的对话框 -->
  <el-dialog v-model="EditDialogVisible" title="修改用户" width="45%" draggable @close="editDialogClosed">
    <el-form ref="editFormRef" :model="editForm" :rules="editRules" label-width="120px" size="large">
      <el-form-item label="id">
        <el-input v-model="editForm.id" disabled/>
      </el-form-item>
      <el-form-item label="读者姓名" prop="readername">
        <el-input v-model.trim="editForm.readername"/>
      </el-form-item>
      <el-form-item label="读者类型" prop="readertype">
        <el-input v-model.trim="editForm.readertype" />
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <!-- <el-input v-model.trim="editForm.sex" /> -->
        <el-select v-model="editForm.sex" placeholder="请选择">
          <el-option label="男" value="男" />
          <el-option label="女" value="女" />
        </el-select>
      </el-form-item>
      <el-form-item label="最大可借数" prop="max_num">
        <el-input v-model.number="editForm.max_num" />
      </el-form-item>
      <el-form-item label="最大可借天数" prop="days_num">
        <el-input v-model.number="editForm.days_num" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="EditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="editReader(editFormRef)">确定</el-button>
      </span>
    </template>
  </el-dialog>

  </div>
</template>

<script setup>
import {useUserStore} from '@/store/userStore.js'
import BreadCrumb from '@/components/common/BreadCrumb.vue'
import { ElMessageBox } from 'element-plus'
import {getAllReaders,getReaderByNameKey,register,deleteReader,getReaderById,
  updateReader,getReaderByMaxNum,getReaderByMaxDay
} from '@/network/reader.js'
import { onMounted, reactive, ref } from 'vue';
import { messageApi } from '../api/global';

//* 变量声明
const userStore = useUserStore()
let data = ref([]) // 读者信息数据
const select = ref('1')  // 下拉选择
const input = ref('') // 文本输入框值 -- 
const AddDialogVisible = ref(false)  // 控制添加对话框的显示和隐藏
const addFormRef = ref(null)  // 添加读者对话框的引用
let addForm = reactive({
  readername: '',
  readertype: '',
  sex: '',
  max_num: '',
  days_num: ''
}) // 添加读者的表单数据 ---
const EditDialogVisible = ref(false)  // 控制修改读者对话框的显示和隐藏
let editForm = ref({})// 修改读者的表单数据
const editFormRef = ref(null)  // 修改读者对话框的引用
// 添加读者的表单规则
const addRules = reactive({
  readername: [
    { required: true, message: '请输入读者姓名', trigger: 'blur' },
    { min: 1, max: 10, message: '姓名的长度在1~10个字符之间', trigger: 'blur' }
  ],
  readertype: [
    { required: true, message: '请输入读者类型', trigger: 'blur' },
    { min: 1, max: 8, message: '类型的长度在1~8个字符之间', trigger: 'blur' }
  ],
  sex: [
    { required: true, message: '请输入性别', trigger: 'blur' },
    { max: 1, message: '性别男/女', trigger: 'blur' }
  ],
  max_num: [
    { required: true, message: '请输入最大可借数', trigger: 'blur' },
    { type: 'number', min: 3, max: 30, message: '请输入数字，可借数在3~30之间', trigger: 'blur' }
  ],
  days_num: [
    { required: true, message: '请输入最大可借天数', trigger: 'blur' },
    { type: 'number', min: 10, max: 360, message: '请输入数字，可借天数在10~360天之间', trigger: 'blur' }
  ],
})
// 修改读者的表单规则
const editRules = reactive({
  readername: [
    { required: true, message: '请输入读者姓名', trigger: 'blur' },
    { min: 1, max: 10, message: '姓名的长度在1~10个字符之间', trigger: 'blur' }
  ],
  readertype: [
    { required: true, message: '请输入读者类型', trigger: 'blur' },
    { min: 1, max: 8, message: '类型的长度在1~8个字符之间', trigger: 'blur' }
  ],
  sex: [
    { required: true, message: '请输入性别', trigger: 'blur' },
    { max: 1, message: '性别男/女', trigger: 'blur' }
  ],
  max_num: [
    { required: true, message: '请输入最大可借数', trigger: 'blur' },
    { type: 'number', min: 3, max: 30, message: '请输入数字，可借数在3~30之间', trigger: 'blur' }
  ],
  days_num: [
    { required: true, message: '请输入最大可借天数', trigger: 'blur' },
    { type: 'number', min: 10, max: 360, message: '请输入数字，可借天数在10~360天之间', trigger: 'blur' }
  ],
})


//* 事件处理

// 获取所有读者信息
const getReaders = async () => {
  const { data: res} = await getAllReaders()
  data.value = res.data
}

// 查询读者
const searchReader = async () => {
  // 读者 id 查询
    if (select.value === "1") {
    if (input.value === '' )  return getReaders()
    const flag = Number.isInteger(Number(input.value))
    if (!flag) return messageApi('warning', '请输入数字！')
    const {data:res} = await getReaderById(input.value)
    if (res.code !== 200) return messageApi('error', res.msg)
    data.value = []
    data.value.push(res.data)
  } 
  // 读者姓名模糊查询
  if (select.value === "2") {
    const {data:res} = await getReaderByNameKey({readerkey: input.value})
    if (res.code !== 200) return messageApi('error', res.msg)
    data.value = res.data
  }
  // 最大可借数
  if (select.value === "3") {
    if (input.value === '' )  return getReaders()
    const flag = Number.isInteger(Number(input.value))
    if (!flag) return messageApi('warning', '请输入数字！')
    const {data:res} = await getReaderByMaxNum({max_num: input.value})
    if (res.code !== 200) return messageApi('error', res.msg)
    data.value = res.data
  } 
  // 最大可借天数
  if (select.value === "4") {
    if (input.value === '' )  return getReaders()
    const flag = Number.isInteger(Number(input.value))
    if (!flag) return messageApi('warning', '请输入数字！')
    const {data:res} = await getReaderByMaxDay({days_num: input.value})
    if (res.code !== 200) return messageApi('error', res.msg)
    data.value = res.data
  } 
}

// 添加读者
const addReader = async (addRef) => {
  // 先进行预校验
  await addRef.validate( async valid => {
    if (!valid) return Error;
    const {data: res} = await register(addForm)
    if (res.code !== 200) return messageApi('error', res.msg)
    messageApi('success', res.msg)
    getReaders()
    AddDialogVisible.value = false
  })
}

// 添加读者对话框的关闭事件
const addDialogClosed = () => {
  addFormRef.value.resetFields()
}

// 显示修改读者信息的对话框
const handleEdit = async (index, row) => {
  const {data: res} = await getReaderById(row.id)
  if (res.code !== 200) return messageApi('error', '获取用户信息失败！')
  editForm.value = res.data
  EditDialogVisible.value = true
}

// 确认修改用户信息
const editReader = async (editRef) => {
  // 先进行预校验
  await editRef.validate(async valid => {
    if (!valid) return Error;
    // 发起修改请求
    const {data: res} = await updateReader(editForm.value)
    if (res.code !== 200) return messageApi('error', res.msg);
    getReaders()
    messageApi('success', res.msg)
    EditDialogVisible.value = false
  })
}

// 修改用户对话框的关闭事件
const editDialogClosed = () => {
  editFormRef.value.resetFields()
}

// 删除读者
const handleDelete = async (index, row) => {
  try{
    await ElMessageBox.confirm( `确认删除读者 “${row.readername}” 吗？`, '警告', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
    // 发起删除读者的请求
    const {data: res} = await deleteReader(row.id);
    if (res.code !== 200) return messageApi('error', '删除用户失败！')
    messageApi('success', res.msg)
    getReaders()
  }catch(e) {
    messageApi('info', '已取消')
  }
}

onMounted(() => {
  getReaders()
})

</script>

<style lang="less" scoped>
.reader {
  height: 100%;
  width: 85%;
  background-color: #eaedf1;

}
.content {
  width: 100%;
  // height: 600px;
  margin: 0 15px;
  background: #fff;
  overflow: auto;
  width:  1300px;

  .el-card {
    width: 100%;
  }
  .el-table {
    width: 100%
  }
  .el-row {
    margin-bottom: 10px;
  }
}

.input-with-select .el-input-group__prepend {
  background-color: var(--el-fill-color-blank);
}
</style>